import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { get } from '@shared/utils/apiClient';
import { ApiResponse } from '@shared/types/market';

interface Bar {
  timestamp: string;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
  amount: number;
}

interface IndexBarsData {
  code: string;
  name: string;
  period: string;
  bars: Bar[];
  total: number;
}

interface IndexChartProps {
  code?: string;
  period?: string;
  height?: number;
}

const API_BASE = (import.meta as any).env?.VITE_API_BASE_URL || '';

const IndexChart: React.FC<IndexChartProps> = ({ 
  code = '000001.SH',
  period = '5m',
  height = 400,
}) => {
  const indexNames: Record<string, string> = {
    '000001.SH': '上证指数',
    '399001.SZ': '深证成指',
    '399006.SZ': '创业板指',
    'HSI': '恒生指数',
  };

  // 获取K线数据
  const { data, isLoading, error } = useQuery({
    queryKey: ['indexBars', code, period],
    queryFn: async () => {
      const response = await get<ApiResponse<IndexBarsData>>(
        `${API_BASE}/api/v1/market/index-bars?code=${code}&period=${period}&limit=120`
      );
      return response.data;
    },
    refetchInterval: period === '1m' || period === '5m' ? 30000 : false,
    staleTime: period === '1m' || period === '5m' ? 15000 : 300000,
  });

  // 使用真实数据
  const displayData = data || {
    code,
    name: indexNames[code] || code,
    period,
    bars: [],
    total: 0,
  };

  // 计算统计数据
  const latestBar = displayData.bars[displayData.bars.length - 1];
  const firstBar = displayData.bars[0];
  const priceChange = latestBar ? latestBar.close - firstBar.open : 0;
  const priceChangePct = firstBar ? (priceChange / firstBar.open) * 100 : 0;
  const isPositive = priceChange >= 0;

  return (
    <div
      style={{
        backgroundColor: 'white',
        borderRadius: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        padding: '24px',
      }}
    >
      {/* 头部信息 */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '20px',
          paddingBottom: '16px',
          borderBottom: '1px solid #f0f0f0',
        }}
      >
        <div>
          <h3 style={{ margin: 0, fontSize: '18px', fontWeight: '600', color: '#333' }}>
            📈 {displayData.name}
          </h3>
          {latestBar && (
            <div style={{ marginTop: '8px', display: 'flex', alignItems: 'center', gap: '12px' }}>
              <span style={{ fontSize: '24px', fontWeight: '700', color: '#333' }}>
                {latestBar.close.toFixed(2)}
              </span>
              <span
                style={{
                  fontSize: '16px',
                  fontWeight: '600',
                  color: isPositive ? '#ef4444' : '#10b981',
                }}
              >
                {isPositive ? '↑' : '↓'} {Math.abs(priceChange).toFixed(2)} ({isPositive ? '+' : ''}
                {priceChangePct.toFixed(2)}%)
              </span>
            </div>
          )}
          {!latestBar && !isLoading && (
            <div style={{ marginTop: '8px', fontSize: '14px', color: '#999' }}>
              数据暂时不可用
            </div>
          )}
        </div>
      </div>

      {/* 图表区域 */}
      <div className="relative" style={{ height: `${height}px` }}>
        {isLoading && (
          <div
            style={{
              position: 'absolute',
              inset: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: '#fafafa',
              borderRadius: '8px',
            }}
          >
            <div style={{ textAlign: 'center' }}>
              <div
                style={{
                  width: '40px',
                  height: '40px',
                  border: '4px solid #f0f0f0',
                  borderTopColor: '#1890ff',
                  borderRadius: '50%',
                  animation: 'spin 1s linear infinite',
                  margin: '0 auto 12px',
                }}
              />
              <div style={{ color: '#999', fontSize: '14px' }}>加载中...</div>
            </div>
          </div>
        )}

        {!isLoading && error && (
          <div
            style={{
              height: '100%',
              border: '2px solid #fee2e2',
              borderRadius: '8px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              background: 'linear-gradient(180deg, #fef2f2 0%, #ffffff 100%)',
            }}
          >
            <div style={{ textAlign: 'center', color: '#ef4444' }}>
              <div style={{ fontSize: '48px', marginBottom: '12px' }}>⚠️</div>
              <div style={{ fontSize: '16px', fontWeight: '500', marginBottom: '8px' }}>
                K线数据暂时不可用
              </div>
              <div style={{ fontSize: '14px', color: '#f87171' }}>
                请稍后再试或检查网络连接
              </div>
            </div>
          </div>
        )}

        {!isLoading && !error && displayData.bars.length === 0 && (
          <div
            style={{
              height: '100%',
              border: '2px dashed #e0e0e0',
              borderRadius: '8px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              background: 'linear-gradient(180deg, #fafafa 0%, #ffffff 100%)',
            }}
          >
            <div style={{ textAlign: 'center', color: '#999' }}>
              <div style={{ fontSize: '48px', marginBottom: '12px' }}>📊</div>
              <div style={{ fontSize: '16px', fontWeight: '500', marginBottom: '8px' }}>
                K线图表区域
              </div>
              <div style={{ fontSize: '14px', color: '#bbb' }}>
                暂无数据
              </div>
              <div style={{ fontSize: '12px', color: '#d0d0d0', marginTop: '4px' }}>
                (待集成 ECharts 或 TradingView)
              </div>
            </div>
          </div>
        )}

        {!isLoading && !error && displayData.bars.length > 0 && (
          <div
            style={{
              height: '100%',
              border: '2px dashed #e0e0e0',
              borderRadius: '8px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              background: 'linear-gradient(180deg, #fafafa 0%, #ffffff 100%)',
            }}
          >
            <div style={{ textAlign: 'center', color: '#999' }}>
              <div style={{ fontSize: '48px', marginBottom: '12px' }}>📊</div>
              <div style={{ fontSize: '16px', fontWeight: '500', marginBottom: '8px' }}>
                K线图表区域
              </div>
              <div style={{ fontSize: '14px', color: '#bbb' }}>
                共 {displayData.total} 条数据点 · {period} 周期
              </div>
              <div style={{ fontSize: '12px', color: '#d0d0d0', marginTop: '4px' }}>
                (待集成 ECharts 或 TradingView)
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 成交量图（占位） */}
      <div className="mt-4" style={{ height: '80px' }}>
        <div
          style={{
            height: '100%',
            border: '1px solid #e8e8e8',
            borderRadius: '6px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#fafafa',
          }}
        >
          <span style={{ fontSize: '13px', color: '#999' }}>📊 成交量</span>
        </div>
      </div>

      {/* 数据摘要 */}
      {latestBar && (
        <div
          style={{
            marginTop: '16px',
            display: 'grid',
            gridTemplateColumns: 'repeat(4, 1fr)',
            gap: '12px',
            padding: '12px',
            backgroundColor: '#fafafa',
            borderRadius: '6px',
            fontSize: '13px',
          }}
        >
          <div>
            <div style={{ color: '#999', marginBottom: '4px' }}>开盘</div>
            <div style={{ color: '#333', fontWeight: '600' }}>{latestBar.open.toFixed(2)}</div>
          </div>
          <div>
            <div style={{ color: '#999', marginBottom: '4px' }}>最高</div>
            <div style={{ color: '#ef4444', fontWeight: '600' }}>{latestBar.high.toFixed(2)}</div>
          </div>
          <div>
            <div style={{ color: '#999', marginBottom: '4px' }}>最低</div>
            <div style={{ color: '#10b981', fontWeight: '600' }}>{latestBar.low.toFixed(2)}</div>
          </div>
          <div>
            <div style={{ color: '#999', marginBottom: '4px' }}>成交量</div>
            <div style={{ color: '#333', fontWeight: '600' }}>
              {(latestBar.volume / 100000000).toFixed(2)}亿
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default IndexChart;
